<template>
  <BasicDrawer v-bind="$attrs" @register="register" :title="displayModuleTitle" width="90%">
    <a-row class="a-row">
      <a-col :span="7">
        <a-row
          ><a-col :span="24">
            <a-card>
              <div :id="'static-' + deptid" style="width: 100%; height: 600px; min-height: 600px">
              </div>
            </a-card>
          </a-col>
        </a-row>
      </a-col>
      <a-col :span="17">
        <a-row class="a-row">
          <a-col :span="23">
            <div class="flexBetween">
              <div></div>
              <a-radio-group
                v-model:value="choosetmType"
                style="margin: 0 5px 5px 0"
                button-style="solid"
                @change="changeChooseTm"
              >
                <a-radio-button value="1">本月</a-radio-button>
                <a-radio-button value="2">下个月</a-radio-button>
                <a-radio-button value="3">本季度</a-radio-button>
                <a-radio-button value="4">本年</a-radio-button>
              </a-radio-group>
            </div>
          </a-col>
        </a-row>
        <s-row class="a-row">
          <a-col :span="23">
            <a-card
              title="隐患治理"
              @click="gotoTroubleLedger"
              :headStyle="{ fontSize: '15px', fontWeight: 'bold' }"
            >
              <a-card-grid style="width: 50%; text-align: center">
                <div
                  id="deptTroubleChartDom1"
                  style="width: 100%; height: 250px; min-height: 250px"
                >
                </div>
              </a-card-grid>
              <a-card-grid style="width: 50%; text-align: center">
                <div
                  id="deptTroubleChartDom2"
                  style="width: 100%; height: 250px; min-height: 250px"
                >
                </div
              ></a-card-grid>
            </a-card>
          </a-col>
        </s-row>
        <s-row class="a-row">
          <a-col :span="23">
            <a-card
              title="任务"
              :headStyle="{ fontSize: '15px', fontWeight: 'bold' }"
              @click="gotoTaskLedger"
              ><a-card-grid style="width: 50%; text-align: center">
                <div id="deptTaskChartDom1" style="width: 100%; height: 250px; min-height: 250px">
                </div
              ></a-card-grid>
              <a-card-grid style="width: 50%; text-align: center"
                ><div id="deptTaskChartDom2" style="width: 100%; height: 250px; min-height: 250px">
                </div>
              </a-card-grid>
              <a-card-grid style="width: 100%; text-align: center"
                ><div id="deptTaskChartDom3" style="width: 100%; height: 300px; min-height: 300px">
                </div>
              </a-card-grid>
            </a-card>
          </a-col>
        </s-row>
      </a-col>
    </a-row>
    <DeptBoardDrawer @register="registerDeptBoardDrawer" />
  </BasicDrawer>
</template>

<script lang="ts">
  import { defineComponent, ref, unref, computed, reactive, onMounted } from 'vue';
  import { BasicDrawer, useDrawerInner, useDrawer } from '/@/components/Drawer';
  import { PageWrapper } from '/@/components/Page';
  import { BasicTable, TableAction, useTable } from '/@/components/Table/index';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { displayTitle } from '/@/utils/QcUnifyUtil';
  import { queryChildDeptsEhsBoard } from '/@/api/ehs/ehsBoard';
  import * as echarts from 'echarts';
  import { useRouter } from 'vue-router';
  import moment from 'moment';
  export default defineComponent({
    components: { BasicDrawer, BasicTable, PageWrapper },
    setup() {
      var hazardChartDom = null;
      var deptTroubleChartDom1 = null;
      var deptTroubleChartDom2 = null;
      var deptTaskChartDom1 = null;
      var deptTaskChartDom2 = null;
      var deptTaskChartDom3 = null;
      const router = useRouter();
      const deptOrgBoardData = ref([]);
      const deptName = ref('');
      const deptid = ref('');
      const orgcode = ref('');
      const choosetmType = ref('4');
      const queryTm = ref([
        moment().startOf('year').format('YYYY-MM-DD'),
        moment().endOf('year').format('YYYY-MM-DD'),
      ]);
      const chartData = ref({
        hazard: [],
        trouble: [],
        task: [],
      });

      const [registerDeptBoardDrawer, { openDrawer: openDeptBoardDrawer }] = useDrawer();

      function changeChooseTm(e) {
        let op = {
          1: [
            moment().startOf('month').format('YYYY-MM-DD'),
            moment().endOf('month').format('YYYY-MM-DD'),
          ],
          2: [
            moment().subtract(-1, 'month').startOf('month').format('YYYY-MM-DD'),
            moment().subtract(-1, 'month').endOf('month').format('YYYY-MM-DD'),
          ],
          3: [
            moment().startOf('quarter').format('YYYY-MM-DD'),
            moment().endOf('quarter').format('YYYY-MM-DD'),
          ],
          4: [
            moment().startOf('year').format('YYYY-MM-DD'),
            moment().endOf('year').format('YYYY-MM-DD'),
          ],
        };
        queryTm.value = op[e.target.value];
        search();
      }

      function search() {
        queryChildDeptsEhsBoard({
          orgcode: orgcode.value,
          begintm: queryTm.value[0],
          endtm: queryTm.value[1],
          deptid: deptid.value,
        }).then((res) => {
          deptOrgBoardData.value = res;
          chartData.value.hazard = res.map((item) => {
            return {
              name: item.name,
              value: item.hazard?.count ?? 0,
            };
          });
          chartData.value.trouble = res.map((item) => {
            return {
              name: item.name,
              value: item.trouble?.count ?? 0,
            };
          });
          hazardChartDom = document.getElementById('static-' + deptid.value);
          deptTroubleChartDom1 = document.getElementById('deptTroubleChartDom1');
          deptTaskChartDom1 = document.getElementById('deptTaskChartDom1');
          deptTroubleChartDom2 = document.getElementById('deptTroubleChartDom2');
          deptTaskChartDom2 = document.getElementById('deptTaskChartDom2');
          deptTaskChartDom3 = document.getElementById('deptTaskChartDom3');
          let myChart = echarts.init(hazardChartDom);
          let troubleChart1 = echarts.init(deptTroubleChartDom1);
          let troubleChart2 = echarts.init(deptTroubleChartDom2);
          let taskChart1 = echarts.init(deptTaskChartDom1);
          let taskChart2 = echarts.init(deptTaskChartDom2);
          let taskChart3 = echarts.init(deptTaskChartDom3);
          let option = {
            title: [
              {
                text: '危险源',
                left: '50%',
                top: '0%',
                textAlign: 'center',
              },
              {
                text: '隐患',
                left: '50%',
                top: '50%',
                textAlign: 'center',
              },
            ],
            tooltip: {
              trigger: 'item',
            },
            // legend: {
            //   top: 'bottom',
            // },
            toolbox: {
              show: false,
            },
            series: [
              {
                name: '危险源',
                type: 'pie',
                radius: '40%',
                center: ['50%', '25%'],
                label: {
                  formatter: '{b}\n({d}%)',
                },
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)',
                  },
                },
                data: chartData.value.hazard ?? [],
              },
              {
                name: '隐患',
                type: 'pie',
                radius: '40%',
                center: ['50%', '75%'],
                label: {
                  formatter: '{b}\n({d}%)',
                },
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)',
                  },
                },
                data: chartData.value.trouble ?? [],
              },
            ],
          };
          let troubleOption1 = {
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                // Use axis to trigger tooltip
                type: 'shadow', // 'shadow' as default; can also be 'line' or 'shadow'
              },
            },
            legend: {},
            grid: {
              left: '1%',
              right: '1%',
              bottom: '1%',
              top: '15%',
              containLabel: true,
            },
            xAxis: {
              type: 'category',
              axisLabel: {
                color: '#6c706f',
                interval: 0,
                formatter: function (value) {
                  return value.split('').join('\n');
                },
              },
              data: res.map((item) => item.name),
            },
            yAxis: {
              type: 'value',
              minInterval: 1,
            },
            color: ['#7ec5ff', '#ffc443', '#e15252'],
            series: [
              {
                type: 'bar',
                stack: 'total',
                barWidth: '30px',
                label: {
                  show: true,
                },
                emphasis: {
                  focus: 'series',
                },
                data: res.map((item) => {
                  return item.troublecorrect.correctcount;
                }),
                name: '已整改',
              },
              {
                name: '未整改',
                type: 'bar',
                barWidth: '30px',
                stack: 'total',
                label: {
                  show: true,
                },
                emphasis: {
                  focus: 'series',
                },
                data: res.map((item) => {
                  return item.troublecorrect.count - item.troublecorrect.correctcount;
                }),
              },
            ],
          };
          let troubleOption2 = {
            tooltip: {
              trigger: 'item',
              formatter: '{b}:{c}%',
            },
            grid: {
              left: '1%',
              right: '1%',
              bottom: '1%',
              top: '15%',
              containLabel: true,
            },
            xAxis: {
              type: 'category',
              axisLabel: {
                color: '#6c706f',
                interval: 0,
                formatter: function (value) {
                  return value.split('').join('\n');
                },
              },
              data: res.map((item) => item.name),
            },
            yAxis: {
              name: '整改完成率',
              type: 'value',
              axisLabel: {
                formatter: '{value} %',
              },
              max: 100,
            },
            series: [
              {
                data: res.map((item) =>
                  item.troublecorrect.count == 0
                    ? 100
                    : Number(
                        (item.troublecorrect.correctcount / item.troublecorrect.count) * 100,
                      ).toFixed(0),
                ),
                barMinHeight: 1,
                type: 'bar',
                label: {
                  show: true,
                  formatter: '{c}%',
                },
              },
            ],
          };
          let taskOption1 = {
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                // Use axis to trigger tooltip
                type: 'shadow', // 'shadow' as default; can also be 'line' or 'shadow'
              },
            },
            legend: {},
            grid: {
              left: '1%',
              right: '1%',
              bottom: '1%',
              top: '15%',
              containLabel: true,
            },
            xAxis: {
              type: 'category',
              axisLabel: {
                color: '#6c706f',
                interval: 0,
                formatter: function (value) {
                  return value.split('').join('\n');
                },
              },
              data: res.map((item) => item.name),
            },
            yAxis: {
              type: 'value',
              minInterval: 1,
            },
            color: ['#7ec5ff', '#ffc443', '#e15252'],
            series: [
              {
                type: 'bar',
                stack: 'total',
                barWidth: '30px',
                label: {
                  show: true,
                },
                emphasis: {
                  focus: 'series',
                },
                data: res.map((item) => {
                  return item.task.finishcount;
                }),
                name: '已完成',
              },
              {
                type: 'bar',
                stack: 'total',
                barWidth: '30px',
                label: {
                  show: true,
                },
                emphasis: {
                  focus: 'series',
                },
                data: res.map((item) => {
                  return item.task.timeoutfinishcount;
                }),
                name: '超时完成',
              },
              {
                name: '未完成',
                type: 'bar',
                stack: 'total',
                label: {
                  show: true,
                },
                emphasis: {
                  focus: 'series',
                },
                data: res.map((item) => {
                  return item.task.count - item.task.finishcount - item.task.timeoutfinishcount;
                }),
              },
            ],
          };
          let taskOption2 = {
            tooltip: {
              trigger: 'item',
              formatter: '{b}:{c}%',
            },
            grid: {
              left: '1%',
              right: '1%',
              bottom: '1%',
              top: '15%',
              containLabel: true,
            },
            xAxis: {
              type: 'category',
              axisLabel: {
                color: '#6c706f',
                interval: 0,
                formatter: function (value) {
                  return value.split('').join('\n');
                },
              },
              data: res.map((item) => item.name),
            },
            yAxis: {
              name: '任务完成率',
              type: 'value',
              axisLabel: {
                formatter: '{value} %',
              },
              max: 100,
            },
            series: [
              {
                data: res.map((item) =>
                  item.task.count == 0
                    ? 100
                    : Number(
                        ((item.task.finishcount + item.task.timeoutfinishcount) / item.task.count) *
                          100,
                      ).toFixed(0),
                ),
                barMinHeight: 1,
                type: 'bar',
                label: {
                  show: true,
                  formatter: '{c}%',
                },
              },
            ],
          };
          let taskOption3 = {
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                // Use axis to trigger tooltip
                type: 'shadow', // 'shadow' as default; can also be 'line' or 'shadow'
              },
            },
            legend: {},
            grid: {
              left: '1%',
              right: '1%',
              bottom: '1%',
              containLabel: true,
            },
            xAxis: {
              type: 'category',
              axisLabel: {
                color: '#6c706f',
                interval: 0,
                formatter: function (value) {
                  return value.split('').join('\n');
                },
              },
              data: res.map((item) => item.name),
            },
            yAxis: {
              minInterval: 1,
              type: 'value',
            },
            series: [
              {
                type: 'bar',
                stack: 'total',
                barWidth: '30px',
                label: {
                  show: true,
                },
                emphasis: {
                  focus: 'series',
                },
                data: res.map((item) => {
                  return item.taskcheck.count;
                }),
                name: '自查类',
              },
              {
                type: 'bar',
                stack: 'total',
                barWidth: '30px',
                label: {
                  show: true,
                },
                emphasis: {
                  focus: 'series',
                },
                data: res.map((item) => {
                  return item.taskfacility.count;
                }),
                name: '设备设施类',
              },
              {
                name: '隐患治理类',
                type: 'bar',
                stack: 'total',
                label: {
                  show: true,
                },
                emphasis: {
                  focus: 'series',
                },
                data: res.map((item) => {
                  return item.tasktrouble.count;
                }),
              },
              {
                name: '督察类',
                type: 'bar',
                stack: 'total',
                label: {
                  show: true,
                },
                emphasis: {
                  focus: 'series',
                },
                data: res.map((item) => {
                  return item.taskinspect.count;
                }),
              },
              {
                name: '作业活动类',
                type: 'bar',
                stack: 'total',
                label: {
                  show: true,
                },
                emphasis: {
                  focus: 'series',
                },
                data: res.map((item) => {
                  return item.taskjob.count;
                }),
              },
            ],
          };
          option && myChart.setOption(option);
          troubleOption1 && troubleChart1.setOption(troubleOption1);
          troubleOption2 && troubleChart2.setOption(troubleOption2);
          taskOption1 && taskChart1.setOption(taskOption1);
          taskOption2 && taskChart2.setOption(taskOption2);
          taskOption3 && taskChart3.setOption(taskOption3);
          document.getElementById('static-' + deptid.value).setAttribute('_echarts_instance_', '');
          document.getElementById('deptTroubleChartDom1').setAttribute('_echarts_instance_', '');
          document.getElementById('deptTaskChartDom1').setAttribute('_echarts_instance_', '');
          document.getElementById('deptTroubleChartDom2').setAttribute('_echarts_instance_', '');
          document.getElementById('deptTaskChartDom2').setAttribute('_echarts_instance_', '');
          document.getElementById('deptTaskChartDom3').setAttribute('_echarts_instance_', '');
          window.onresize = function () {
            myChart.resize();
            troubleChart1.resize();
            troubleChart2.resize();
            taskChart1.resize();
            taskChart2.resize();
            taskChart3.resize();
          };
        });
      }

      const qcUnifyProps = ref<QcUnifyTransToChildProps>();
      const [register, { closeDrawer }] = useDrawerInner((data) => {
        if (data != undefined && data != null) {
          let unrefData = unref(data);
          qcUnifyProps.value = unrefData;
          deptName.value = unrefData.deptName;
          deptid.value = unrefData.deptid;
          orgcode.value = unrefData.orgcode;
          search();
        }
      });

      function gotoHazardLedger() {
        router.push({
          path: '/ehs/hazard/dangerledger',
        });
      }

      function gotoTroubleLedger() {
        router.push({
          path: '/ehs/hazard/risksledger',
        });
      }

      function gotoTaskLedger() {
        router.push({
          path: '/ehs/taskConsole',
        });
      }

      function openDeptBoardDrawerButtonClick(item) {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '安全生产看板',
          operateString: item.name,
          deptid: item.deptid,
          deptName: item.name,
          orgcode: orgcode.value,
        };
        openDeptBoardDrawer(true, propsData);
      }

      let displayModuleTitle = computed(() => {
        return displayTitle(qcUnifyProps.value);
      });
      return {
        register,
        displayModuleTitle,
        qcUnifyProps,
        deptOrgBoardData,
        deptName,
        choosetmType,
        changeChooseTm,
        chartData,
        registerDeptBoardDrawer,
        openDeptBoardDrawerButtonClick,
        deptid,
        gotoHazardLedger,
        gotoTroubleLedger,
        gotoTaskLedger,
      };
    },
  });
</script>

<style scoped>
  .flexBetween {
    display: flex;
    width: 100%;
    justify-content: space-between;
    align-items: center;
    flex-direction: row;
    flex-wrap: nowrap;
    margin: 5px;
    padding: 0 10px;
  }

  .boldFont {
    font-size: 25px;
    font-weight: bold;
    margin: 10px;
  }
  .icon {
    font-size: 22px;
    color: #4090ff;
    margin: 5px;
  }
  .a-row {
    margin-bottom: 15px;
    border-radius: 10px;
    display: flex;
    justify-content: space-around;
  }
  ::v-deep(.ant-card-grid) {
    padding: 10px;
  }
</style>
